package com.jumi.microservice.utils;

import com.jumi.microservice.common.exception.BaseException;
import com.jumi.microservice.config.WxPayConfig;
import com.jumi.microservice.exception.PayExceptionEnum;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.net.ssl.SSLContext;
import java.io.IOException;
import java.io.InputStream;
import java.security.KeyStore;

import static com.alibaba.nacos.common.utils.ResourceUtils.getResourceAsStream;

/**
 * @author Scw
 * @Date 2019-09-29 10:25
 */

@Component
public class ClientCustomSsl {
    @Resource
    private WxPayConfig wxPayConfig;

    public String doPost(String url, String data) {
        SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(getSslContext());
        try (CloseableHttpClient httpclient = HttpClients.custom()
                .setSSLSocketFactory(sslConnectionSocketFactory)
                .build()) {
            HttpPost httpPost = new HttpPost(url);
            httpPost.addHeader("Connection", "keep-alive");
            httpPost.addHeader("Accept", "*/*");
            httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
            httpPost.addHeader("Host", "api.mch.weixin.qq.com");
            httpPost.addHeader("X-Requested-With", "XMLHttpRequest");
            httpPost.addHeader("Cache-Control", "max-age=0");
            httpPost.addHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0) ");
            httpPost.setEntity(new StringEntity(data, "UTF-8"));

            try (CloseableHttpResponse response = httpclient.execute(httpPost)) {
                HttpEntity entity = response.getEntity();
                String jsonStr = EntityUtils.toString(response.getEntity(), "UTF-8");
                EntityUtils.consume(entity);
                return jsonStr;
            } catch (IOException e) {
                e.printStackTrace();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        throw new BaseException(PayExceptionEnum.WX_PAY_POST_ERROR);
    }

    private SSLContext getSslContext() {
        try {
            KeyStore keyStore = KeyStore.getInstance("PKCS12");
            try (InputStream is = ClientCustomSsl.class.getClassLoader().getResourceAsStream("apiclient_cert.p12")) {
                keyStore.load(is, wxPayConfig.getMchId().toCharArray());
            }
            return SSLContexts.custom()
                    .loadKeyMaterial(keyStore, wxPayConfig.getMchId().toCharArray())
                    .build();
        } catch (Exception e) {
            e.printStackTrace();
        }
        throw new BaseException(PayExceptionEnum.WX_PAY_POST_ERROR);
    }
}

